package com.wang.home.commons.shiro;

import com.wang.home.commons.util.ShiroUtils;
import com.wang.home.entity.Student;
import com.wang.home.service.MenuService;
import com.wang.home.service.RoleService;
import com.wang.home.service.StudentService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @className: MyShiroRealm
 * @description: 类描述：shiro的自定义realm
 * @author: 作者 wang
 * @date: 2021/4/23 11:59
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private RoleService roleService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private MenuService menuService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
        Student student = (Student) principalCollection.getPrimaryPrincipal();
        System.out.println(")))))))))))))))))))))))))))"+student.getStudentName());
//       授权
        Set<String> roles = roleService.findRolesByStudentName(student.getStudentName());
        authenticationInfo.setRoles(roles);
        System.out.println("00000@@@@@@@@@@@@@￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥（（（（（（（（（（））））））））））））））");
        Set<String> permissions = menuService.findPermissionsByStudentName(student.getStudentName());
        authenticationInfo.setStringPermissions(permissions);

        return authenticationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String name = (String) authenticationToken.getPrincipal();
        System.out.println(name);
        Student student = studentService.getStudentByName(name);
        if (student == null) {
            return null;
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(student, student.getPassword(), ByteSource.Util.bytes(student.getStudentName()), getName());

        ShiroUtils.deleteCache(name, true);
        return simpleAuthenticationInfo;
    }
}
